<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\ShopModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Service\RedisService;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;

class AdminController extends Controller
{
  /*
   * 管理员登录后台系统
   *
   * */
  public function login(Request $request){
      $username=$request->input('username');
      $password=$request->input('password');
      $uinfo=DB::table("jy_admin")->where("username",$username)->where("status",1)->get()->toArray();
      if(!$uinfo){
          $arr=["code"=>0,"msg"=>"帐号不存在","data"=>array()];
          return $arr;
      }
      $password=md5(md5($password).$uinfo[0]->salt);
      if($password != $uinfo[0]->password){
          $arr=["code"=>0,"msg"=>"密码错误","data"=>array()];
          return $arr;
      }

      $id=$uinfo[0]->id;
      $is_super=$uinfo[0]->is_super;

      $menus = DB::table("jy_menus")
              ->where('name','!=','餐饮管理')
              ->where('category','=',1)
              ->where('parentId','=',0);
      $role = "";
      if(!$is_super){
          $role=DB::table("jy_admin_role")->where("role_id",$uinfo[0]->role_id)->first();
          if(!$role){
              $arr=["code"=>0,"msg"=>"管理员未设置角色","data"=>array()];
              return $arr;
          }
          $menus = $menus->whereIn('id',[$role->menu_ids]);
      }
      $menus = $menus->orderBy('sort')->get()->toArray();
      if($menus){
          //更新最后一次登录时间
          $re=DB::table('jy_admin')->where("id",$id)->update(['logintime'=>time()]);
          if($re > 0){}else{return ['code'=>1002,'msg'=>'登录失败'];}

          $token = \Str::random (64);
          $redis = new RedisService();
          $data  = $redis->add($token,$uinfo);

          if($data['code'] != 200){
              return ['code'=>1002,'msg'=>'登录失败'];
          }

//          foreach($menus as $row){
//              $menu_sub= DB::table('jy_menus')->where('category','=',1)->where('parentId','=',$row->id);
//              if($role) $menu_sub =$menu_sub->whereIn('id',[$role->menu_ids]);
//              $menu_sub = $menu_sub->orderBy('sort')->get()->toArray();
//              if($menu_sub)
//                  $row->children=$menu_sub;
//              $data[]=$row;
//          }


          return ['code'=>200,'msg'=>'登录成功','data'=>$token];

      }else{
          return ["code"=>0,"msg"=>"登录失败","data"=>array()];
      }

  }
    /*
        管理员退出
        返回值：
    */
    public function login_out(Request $request){


    }
    /*
       禁用/启用管理员
       参数：id
     */
    public function is_use(Request $request){

        $id=$request->input("id");
        if($id==""){
            $arr=["code"=>0,"msg"=>"id不能为空","data"=>array()];
            return response()->json($arr);
        }
        //查询状态
        $status = DB::table('jy_admin')->where('id',$id)->select('status')->first();
        $data = [];
        if($status->status == 1){
            $data['status'] = 0;
        }else{
            $data['status'] = 1;
        }

        $re=DB::table('jy_admin')->where("id",$id)->update($data);
        if($re>0){
            $arr=["code"=>200,"msg"=>"操作成功","data"=>array()];
        } else
            $arr=["code"=>0,"msg"=>"操作失败","data"=>array()];

        return $arr;

    }


    /*
      注册或编辑管理员
      id: 记录id，传递为修改，不传为增加。
      username:帐号名称
      role_id:角色id
      password:密码,默认为123456
      is_super：是否超级管理员，默认为0，是为1
      status:状态0或1
    */
    public function register(Request $request){
        $data=array();
        $id=$request->input("id")?$request->input("id"):'';
        $data["role_id"]=$request->input("role_id")?$request->input("role_id"):'';
        $data["username"]=$request->input("username")?$request->input("username"):'';
        $data["password"]=$request->input("password")?$request->input("password"):'123456';
        $data["is_super"]=$request->input("is_super")?$request->input("is_super"):'0';
        $data["status"]=$request->input("status")?$request->input("status"):'1';
        $validator=Validator::make($request->input(),[
                    'username'  => ['required','max:10','regex:/^[_\w\d\x{4e00}-\x{9fa5}]{3,20}$/iu'],
                    'password'  => ['required','min:6','regex:/^[a-zA-Z\d_]{6,}$/'],
                    'role_id'  => ['required'],
                ],[
                    'required'=>':attribute为必填项',//:attribute 字段占位符表示字段名称
                    'regex'=>':attribute格式不正确',
                    'unique'=>':attribute已经存在',
                    'max'=>':attribute不能大于10位',
                    'min'=>':attribute不能小于6位',

                ],[
                    'username'=>'用户姓名', //指定字段名称
                    'password'=>'用户密码', //指定字段名称
                    'role_id'=>'用户角色', //指定字段名称
                ]);

                 if($validator->fails()){
                    return ["code"=>422,"msg"=>$validator->errors()->first()];
                 }


        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < 5; $i++){
            $str .= $chars[mt_rand(0, $lc)];
        }
        $data["salt"]=$str;
        $data["password"]=md5(md5($data["password"]).$data["salt"]);
        $data["createtime"]=time();

        if($id){
            $re=DB::table('jy_admin')->where("id",$id)->first();
            if(!$re){
                return ["status"=>0,"msg"=>"用户不存在，请刷新再试~"];
            }
            $mid= DB::table("jy_admin")->where("id",$id)->update($data);
        }else{
            $re_user=DB::table("jy_admin")->where("username",$data["username"])->first();
            if($re_user){
                return ["code"=>0,"msg"=>"添加失败，名称已经存在。"];
            }

            $mid = DB::table("jy_admin")->insertGetId($data);
        }

        if($mid>0)
        {
            $arr=["code"=>1,"msg"=>"添加成功","data"=>[]];
        }else
            $arr=["code"=>0,"msg"=>"添加失败，请检查数据格式是否正确。","data"=>[]];

        return $arr;

    }


    /*
      获取所有管理帐号
      参数：id        记录id
      参数：role_id   所属权限组id
      参数: username 帐号
      参数：status  0、禁用  1、正常
      参数为选填项
    */
    public function get_admin(Request $request){

        $menus = DB::table('jy_admin as a')
               ->leftJoin('jy_admin_role as r','r.role_id','=','a.role_id')
                ->select('a.id','a.username','a.status','a.is_super','r.role_name');

        if($request->input("id")) $menus = $menus->where('a.id','=',$request->input("id"));//获取单条数据详情
        if($request->input("status") && $request->input("status") >= 0) $menus = $menus->where('a.status','=',$request->input("status"));
        if($request->input("role_id")) $menus = $menus->where('a.role_id','=',$request->input("role_id"));
        if($request->input("username")) $menus = $menus->where('a.username','=',$request->input("username"));

        $menus=$menus->orderBy('id')->paginate(5)->toArray();
        if($menus){
            $arr=["code"=>200,"msg"=>"获取数据成功","data"=>$menus];
        }else
            $arr=["code"=>0,"msg"=>"获取数据失败","data"=>[]];

        return $arr;

    }
        /*
          删除角色
          参数：id
        */
    public function del_role(Request $request){

        $id=$request->input("id");
        if($id==""){
            $arr=["code"=>0,"msg"=>"id不能为空"];
            return $arr;
        }
        //判断角色是否还在使用中
        $role_id=DB::table('jy_admin')->where('role_id','=',$id)->first();
        if($role_id){
            $arr=["code"=>0,"msg"=>"角色不允许删除"];
            return $arr;
        }
        $re=DB::table('jy_admin_role')->where("role_id",$id)->delete();
        if($re>0){
            $arr=["code"=>200,"msg"=>"删除成功"];
        } else
            $arr=["code"=>0,"msg"=>"删除失败"];

        return $arr;
    }
    /*
      添加编辑角色
      role_id：角色id,编辑时传递此参。
      role_name:角色名称
      menu_ids:菜单id  多个用逗号分开
    */
    public function addedit_role(Request $request){

        $data = [
            'role_name' => $request->input("role_name"),
            'menu_ids' => $request->input("menu_ids"),
        ];
        if($request->input("role_name") && $request->input("menu_ids")){
            if($request->input("role_id")){

                $mid= DB::table("jy_admin_role")->where("role_id",$request->input("role_id"))->update($data);

            }else {
                $mid = DB::table("jy_admin_role")->insertGetId($data);
            }

        }else{
            $arr=["code"=>0,"msg"=>"保存失败，请检查数据格式是否正确。","data"=>array()];
            return $arr;
        }
        if($mid>0)
        {  $arr=["code"=>200,"msg"=>"保存成功","data"=>array()];}else $arr=["code"=>0,"msg"=>"报错失败，请检查数据格式是否正确。","data"=>array()];

        return $arr;

    }

    /*
      获取角色
      参数
      role_id:角色id
    */
    public function get_role(Request $request){

        $menus = DB::table('jy_admin_role');
        if($request->input("role_id")) $menus = $menus->where('role_id','=',$request->input("role_id"));

        $menus=$menus->orderBy('role_id')->paginate(10);
        if($menus){
            $arr=["code"=>200,"msg"=>"获取数据成功","data"=>$menus];
        }else
            $arr=["code"=>0,"msg"=>"获取数据失败"];

        return $arr;
    }
}


?>